const express = require('express');
const bodyParser = require('body-parser');
const  mysql = require('mysql');
const app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())
const port = process.env.PORT || 9999;

// 引入数据库配置文件
const config = require('./config')

app.get('/', (req, res) => {
    res.send('Hello World!');
})

const connection = mysql.createConnection(config.development);
// get请求，返回json格式list数据
app.get('/get', (req, res) => {
    let sql = 'SELECT * FROM bookbase';
    console.log(req.query.BookName)
    if(req.query.BookName) {
        sql = `SELECT * FROM bookbase WHERE BookName Like '%${req.query.BookName}%'`
    }

    connection.query(sql, (err, result) => {
        // console.log(sql)
        if(err){
            res.send(err);
        }else{
            res.send(result);
        }
    })
})
// post请求，添加
app.post('/add', (req, res) => {
    // console.log(req)
    let sql = `INSERT INTO bookbase (BookName, Author, TypeName, Remarks) VALUES ('${req.body.BookName}', '${req.body.Author}', '${req.body.TypeName}', '${req.body.Remarks}')`;
    connection.query(sql, (err, result) => {
        console.log(sql)
        if(err){
            res.send(err);
        }else{
            res.send(result);
        }
    })
})
// post请求，编辑
app.post('/edit', (req, res) => {
    let sql = `UPDATE bookbase SET BookName = '${req.body.BookName}', Author = '${req.body.Author}', TypeName = '${req.body.TypeName}', Remarks = '${req.body.Remarks}' WHERE Id = '${req.query.Id}'`;
    connection.query(sql, (err, result) => {
        if(err){
            res.send(err);
        }else{
            res.send(result);
        }
    })
})
// get请求，删除
app.get('/del', (req, res) => {
    let sql = `DELETE FROM bookbase  WHERE Id =${req.query.Id}`;
    connection.query(sql, (err, result) => {
        if(err){
            res.send(err);
        }else{
            res.send(result);
        }
    })
})
app.listen(port, () => {
    console.log(`Example app listening on port ${port}`);
})